package com.lihao.wanandroid.ui.web

import android.os.Bundle
import android.view.*
import android.widget.LinearLayout
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.just.agentweb.AgentWeb
import com.lihao.jetpackcore.ext.getViewModel
import com.lihao.jetpackcore.ext.nav
import com.lihao.jetpackcore.util.ToastUtil
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.util.VibrateUtils
import com.lihao.wanandroid.data.model.ArticleResponse
import com.lihao.wanandroid.data.model.BannerResponse
import com.lihao.wanandroid.data.model.CollectEvent
import com.lihao.wanandroid.data.model.enum.CollectType
import com.lihao.wanandroid.ui.collect.CollectViewModel
import kotlinx.android.synthetic.main.fragment_web.*


/**
 * web界面
 */
class WebFragment : BaseFragment<WebViewModel>() {

    private var mAgentWeb: AgentWeb? = null

    private val collectViewModel: CollectViewModel by lazy {
        getViewModel<CollectViewModel>()
    }

    override fun layoutId() = R.layout.fragment_web

    override fun initView(savedInstanceState: Bundle?) {
        setHasOptionsMenu(true)
        arguments?.run {
            getParcelable<ArticleResponse>("articleData")?.let {
                mViewModel.titleStr = it.title
                mViewModel.articleId = it.id
                mViewModel.isCollect = it.collect
                mViewModel.url = it.link
                mViewModel.collectType = CollectType.Article.type
            }
            getParcelable<BannerResponse>(KEY_BANNER)?.let {
                mViewModel.titleStr = it.title
                mViewModel.articleId = it.id
                mViewModel.isCollect = false
                mViewModel.url = it.url
                mViewModel.collectType = CollectType.Url.type
            }
        }
        initTitle(mViewModel.titleStr) {
            nav().navigateUp()
        }
        (activity as? AppCompatActivity)?.setSupportActionBar(toolbar)
    }

    override fun lazyLoadData() {
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(webContainer, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .createAgentWeb()
            .ready()
            .go(mViewModel.url)
        val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                mAgentWeb?.let {
                    if (it.webCreator.webView.canGoBack()) {
                        it.webCreator.webView.goBack()
                    } else {
                        nav().navigateUp()
                    }
                }
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this, callback)
    }

    override fun createObserver() {
        super.createObserver()
        collectViewModel.collectState.observe(this, Observer {
            if (it.isSuccess) {
                ToastUtil.showShort(context, if (it.collect) "收藏成功！" else "取消收藏！")
                eventViewModel.collect.value = CollectEvent(it.id, it.collect)
                mViewModel.isCollect = it.collect
                // 更新Menu的图标
                activity?.window?.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL)
                activity?.invalidateOptionsMenu()
            } else {
                ToastUtil.showShort(context, "操作失败")
            }
        })
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.web_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    /**
     * 用于重新加载Menu
     */
    override fun onPrepareOptionsMenu(menu: Menu) {
        context?.let {
            if (mViewModel.isCollect) {
                menu.findItem(R.id.item_collect).icon =
                    ContextCompat.getDrawable(it, R.drawable.ic_collected)
            } else {
                menu.findItem(R.id.item_collect).icon =
                    ContextCompat.getDrawable(it, R.drawable.ic_uncollect)
            }
        }
        super.onPrepareOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.item_refresh -> {
                mAgentWeb?.urlLoader?.reload()
            }
            R.id.item_collect -> { // 收藏
                VibrateUtils.vibrate(40)
                if (shareViewModel.isLogin.value) {
                    if (mViewModel.isCollect) {
                        if (mViewModel.collectType == CollectType.Article.type) {
                            collectViewModel.uncollectArticle(mViewModel.articleId)
                        } else {
                            collectViewModel.uncollectUrl(mViewModel.articleId)
                        }
                    } else {
                        if (mViewModel.collectType == CollectType.Article.type) {
                            collectViewModel.collectArticleIn(mViewModel.articleId)
                        } else {
                            collectViewModel.collectUrl(mViewModel.titleStr, mViewModel.url)
                        }
                    }
                } else {
                    nav().navigate(R.id.action_to_loginFragment)
                }
            }

            R.id.item_share -> { // 分享

            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroyView() {
        mAgentWeb?.webLifeCycle?.onDestroy()
        super.onDestroyView()
    }

    companion object {
        const val KEY_ARTICLE = "articleData"
        const val KEY_BANNER = "bannerData"
    }
}